window.onload = function () {
  initMap();
  loadData();
  // toggleFullScreen();
};

let map;
const mapZoom = 14;
let shipsData = []; // 存储所有船舶数据
let shipMarkers = []; // 存储船舶标记
let alertMessage = null;
let currentPolyline = null; // 用于存储当前显示的轨迹
let currentSquareMarkers = []; // 用于存储当前显示的小正方形标记

function initMap() {
  map = new BMap.Map('map');
  map.centerAndZoom(new BMap.Point(108.85, 22.85), mapZoom);
  map.setCurrentCity('西江');
  map.enableScrollWheelZoom(true);
  map.enableContinuousZoom(true);
  map.setMapType(BMAP_SATELLITE_MAP);
}

function loadData() {
  const filePath = './files/北斗定位数据for桂林理工.xlsx';
  fetch(filePath)
      .then(response => response.arrayBuffer())
      .then(data => {
        const workbook = XLSX.read(data, { type: 'array' });
        const worksheet = workbook.Sheets[workbook.SheetNames[0]];
        const jsonData = XLSX.utils.sheet_to_json(worksheet);

        // 处理数据：按船舶名称分组，保留每组最早时间的记录
        const shipFirstData = {};
        jsonData.forEach(item => {
          const name = item['NAME'];
          const time = new Date(formatExcelDate(item['GPS_TIME']));
          // 初始化或比较时间，保留最早时间的记录
          if (!shipFirstData[name] || time < new Date(shipFirstData[name].GPS_TIME)) {
            shipFirstData[name] = {
              NAME: name,
              FIX_X: item['FIX_X'],
              FIX_Y: item['FIX_Y'],
              GPS_TIME: formatExcelDate(item['GPS_TIME']),
              AIS_point: jsonData.filter(rec => rec['NAME'] === name).sort((a, b) =>
                  new Date(formatExcelDate(a['GPS_TIME'])) - new Date(formatExcelDate(b['GPS_TIME']))
              )
            };
          }
        });

        shipsData = Object.values(shipFirstData); // 仅保留各船舶最早时间的记录
        addShipMarkers();
      })
      .catch(error => console.error('加载文件时出错:', error));
}

function addShipMarkers() {
  const iconNames = ["sship1.png", "sship2.png", "sship3.png", "sship4.png", "sship5.png"];

  shipsData.forEach(ship => {
    const point = new BMap.Point(ship.FIX_X, ship.FIX_Y);
    const randomIndex = Math.floor(Math.random() * iconNames.length);
    const shipIcon = new BMap.Icon(`./images/${iconNames[randomIndex]}`, new BMap.Size(32, 32));
    const marker = new BMap.Marker(point, { icon: shipIcon });

    // 添加鼠标点击事件：显示或隐藏轨迹和提示信息
    marker.addEventListener('click', () => {
      if (currentPolyline) {
        map.removeOverlay(currentPolyline);
        currentPolyline = null;
      }
      currentSquareMarkers.forEach(marker => {
        map.removeOverlay(marker);
      });
      currentSquareMarkers = [];

      const AIS_point = ship.AIS_point.map(rec => new BMap.Point(rec.FIX_X, rec.FIX_Y));
      currentPolyline = new BMap.Polyline(AIS_point, {
        strokeColor: '#00FF00', // 轨迹颜色为绿色
        strokeWeight: 2,
        strokeOpacity: 0.7,
        strokeStyle: 'dashed' // 虚线样式
      });
      map.addOverlay(currentPolyline);

      // // 添加小正方形表示数据点
      // currentSquareMarkers = AIS_point.map(point => {
      //   const squareIcon = new BMap.Icon('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="8" height="8" fill="green"><rect width="8" height="8"/></svg>', new BMap.Size(8, 8));
      //   const squareMarker = new BMap.Marker(point, { icon: squareIcon });
      //   map.addOverlay(squareMarker);
      //   return squareMarker;
      // });

      // 显示提示信息，添加经纬度信息
      showAlert(`船舶名称: ${ship.NAME}<br>经度: ${ship.FIX_X}<br>纬度: ${ship.FIX_Y}<br>时间: ${ship.GPS_TIME}`);
    });

    map.addOverlay(marker);
    shipMarkers.push(marker);
  });
}

// 日期格式转换（保持不变）
function formatExcelDate(excelDate) {
  const date = new Date((excelDate - 25569) * 86400 * 1000);
  return date.toLocaleString();
}

function showAlert(message) {
  const alertElement = document.getElementById('alert-message');
  alertElement.innerHTML = message;
  alertElement.style.display = 'block';
  // setTimeout(() => { alertElement.style.display = 'none'; }, 3000); // 3秒后隐藏提示
}
